/**
 * @author wizard
 */
package com.unsanctioned.radioagregator.http.utils;

import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URI;

import org.springframework.http.HttpMethod;
import org.springframework.http.client.ClientHttpRequest;
import org.springframework.http.client.SimpleClientHttpRequestFactory;

import android.util.Log;


/**
 * This class defines request which will be used to create RestTemplate instance with
 * certain property.
 * 
 * @author wizard
 *
 */
public class ClientRequestFactory extends SimpleClientHttpRequestFactory {
	public static final String DOGTAG = ClientRequestFactory.class.getSimpleName();
	private String headerValue = null, headerName = null;
	private String[] headerValues = null, headerNames = null;
	private int defaultTimeout = 5 * 1000;
	/**
	 * Default constructor.
	 * @param headerName - name of value you want to insert into this request.
	 * @param headerValue - the value itself.
	 */
	public ClientRequestFactory(String headerName, String headerValue) {
		this.headerName = headerName;
		this.headerValue = headerValue;
		// Log.i(TAG, this.headerName + " : " + this.headerValue);
	}
	/**
	 * Secondary constructor if you need to insert multiple names with their value.
	 * @param headerNames - an array of name of value you want to insert into this request.
	 * @param headerValues - an array of value itself.
	 */
	public ClientRequestFactory(String[] headerNames, String[] headerValues) {
		this.headerValues = headerValues;
		this.headerNames = headerNames;
	}
	
	@Override
	public void setReadTimeout(int readTimeout) {
		// TODO Auto-generated method stub
		super.setReadTimeout(defaultTimeout);
	}
	
	@Override
	public void setConnectTimeout(int connectTimeout) {
		// TODO Auto-generated method stub 
		super.setConnectTimeout(defaultTimeout);
	}
	
	@Override
	public ClientHttpRequest createRequest(URI uri, HttpMethod httpMethod) throws IOException {
		// TODO Auto-generated method stub
		return super.createRequest(uri, httpMethod);
	}

	@Override
	protected void prepareConnection(HttpURLConnection connection, String httpMethod) throws IOException {
		// TODO Auto-generated method stub
		int size = 0;
		if(this.headerValues != null && this.headerNames != null) {
			if(this.headerValues.length == this.headerNames.length) {
				size = this.headerValues.length;
				for(int i=0; i<size; ++i) {
					Log.i(DOGTAG,"[" + i +"]" + headerNames[i] + " :: " + headerValues[i]);
					connection.setRequestProperty(headerNames[i], headerValues[i]);
				}
			}			
		}
		if(this.headerName != null && this.headerValue != null) {
			Log.i(DOGTAG, headerName + " :: " + headerValue);
			connection.setRequestProperty(headerName, headerValue);	
		}
		setConnectTimeout(defaultTimeout);
		setReadTimeout(defaultTimeout);
		super.prepareConnection(connection, httpMethod);
	}
}
